package day07.concurrent04;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Demo04 {
    static String name = "小明";
    static String gender = "男";
    static ReadWriteLock lock = new ReentrantReadWriteLock();
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    lock.readLock().lock();
                    System.out.println("线程1开始打印..");
                    //try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace(); }
                    System.out.println("线程1#name:"+name+",gender:"+gender);
                    lock.readLock().unlock();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    lock.readLock().lock();
                    System.out.println("线程2开始打印..");
                    //try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace(); }
                    System.out.println("线程2#name:"+name+",gender:"+gender);
                    lock.readLock().unlock();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    lock.writeLock().lock();
                    if("小明".equals(name)){
                        name = "小花";
                        gender = "女";
                    }else{
                        name = "小明";
                        gender = "男";
                    }
                    lock.writeLock().unlock();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    lock.writeLock().lock();
                    name = "大壮";
                    gender = "未知";
                    lock.writeLock().unlock();
                }
            }
        }).start();
    }
}
